<template>
  <view class="detail-container">
    <!-- 查验结果卡片 -->
    <view class="result-card" :class="resultCardClass">
      <view class="result-icon">
        <uni-icons :type="resultIcon" size="60" color="#fff"></uni-icons>
      </view>
      <view class="result-info">
        <view class="result-title">{{ resultTitle }}</view>
        <view class="result-desc">{{ resultDesc }}</view>
      </view>
    </view>

    <!-- 基本信息 -->
    <view class="info-section">
      <view class="section-header">
        <view class="section-title">基本信息</view>
      </view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">预约编号</text>
          <text class="value">{{ detail.applyNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">商户名称</text>
          <text class="value">{{ detail.merchantName }}</text>
        </view>
        <view class="info-item">
          <text class="label">查验时间</text>
          <text class="value">{{ detail.checkTime }}</text>
        </view>
        <view class="info-item">
          <text class="label">查验人员</text>
          <text class="value">{{ detail.checkUserName || '系统自动' }}</text>
        </view>
        <view class="info-item">
          <text class="label">入场地点</text>
          <text class="value">{{ detail.entryPlace }}</text>
        </view>
        <view class="info-item">
          <text class="label">车牌号</text>
          <text class="value">{{ detail.vehicleNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">联系电话</text>
          <text class="value">{{ detail.contactPhone }}</text>
        </view>
      </view>
    </view>

    <!-- 商品明细 -->
    <view class="info-section">
      <view class="section-header">
        <view class="section-title">商品明细</view>
        <view v-if="detail.checkStatus === '1'" class="section-badge">
          <uni-icons type="eye" size="14" color="#faad14"></uni-icons>
          <text>需抽检</text>
        </view>
      </view>
      <view class="goods-list">
        <view v-for="(goods, index) in detail.goodsList" :key="index" class="goods-item">
          <view class="goods-header">
            <text class="goods-name">{{ goods.goodsName }}</text>
            <view v-if="goods.needInspection === '1'" class="inspect-tag">
              <uni-icons type="eye" size="12" color="#fff"></uni-icons>
              <text>抽检</text>
            </view>
          </view>
          <view class="goods-info">
            <view class="goods-row">
              <text class="goods-label">数量：</text>
              <text class="goods-value">{{ goods.quantity }}{{ goods.unit }}</text>
            </view>
            <view class="goods-row">
              <text class="goods-label">供货商：</text>
              <text class="goods-value">{{ goods.supplierName }}</text>
            </view>
            <view class="goods-row">
              <text class="goods-label">产地：</text>
              <text class="goods-value">{{ goods.originPlace || '未填写' }}</text>
            </view>
            <view v-if="goods.inspectionStatus === '1'" class="inspection-result">
              <view class="result-row">
                <uni-icons type="checkbox-filled" size="14" color="#52c41a"></uni-icons>
                <text>检测结果：合格</text>
              </view>
              <view v-if="goods.inspectionTime" class="result-row">
                <text>检测时间：{{ goods.inspectionTime }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 凭证信息 -->
    <view class="info-section" v-if="detail.certificates && detail.certificates.length > 0">
      <view class="section-header">
        <view class="section-title">相关凭证</view>
      </view>
      <view class="cert-grid">
        <view v-for="(cert, index) in detail.certificates" :key="index" class="cert-item" @click="previewImage(cert)">
          <image :src="cert.url" mode="aspectFill" class="cert-image"></image>
          <view class="cert-name">{{ cert.name }}</view>
        </view>
      </view>
    </view>

    <!-- 查验记录 -->
    <view class="info-section">
      <view class="section-header">
        <view class="section-title">查验记录</view>
      </view>
      <view class="timeline">
        <view v-for="(record, index) in checkRecords" :key="index" class="timeline-item">
          <view class="timeline-dot" :class="index === 0 ? 'active' : ''"></view>
          <view class="timeline-content">
            <view class="timeline-title">{{ record.title }}</view>
            <view class="timeline-desc">{{ record.desc }}</view>
            <view class="timeline-time">
              <uni-icons type="calendar" size="12" color="#999"></uni-icons>
              <text>{{ record.time }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作 -->
    <view v-if="detail.checkStatus === '1' && canInspect" class="bottom-actions">
      <view class="action-btn primary-btn" @click="handleInspection">
        <uni-icons type="compose" size="20" color="#fff"></uni-icons>
        <text>录入抽检结果</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getCheckRecord } from '@/api/business/check.js'
import { getAppointment } from '@/api/business/appointment.js'
import storage from '@/utils/storage'
import constant from '@/utils/constant'

export default {
  data() {
    return {
      checkId: '',
      applyId: '',
      detail: {
        checkStatus: '0',
        goodsList: [],
        certificates: []
      },
      checkRecords: []
    }
  },
  computed: {
    // 是否可以录入抽检结果
    canInspect() {
      const roles = storage.get(constant.roles) || []
      const roleKeys = roles.map(r => typeof r === 'object' ? r.roleKey : r)
      return roleKeys.includes('inspector') || roleKeys.includes('admin')
    },
    // 结果卡片样式
    resultCardClass() {
      const map = {
        '0': 'green-card',
        '1': 'yellow-card',
        '2': 'red-card'
      }
      return map[this.detail.checkStatus] || 'green-card'
    },
    // 结果图标
    resultIcon() {
      const map = {
        '0': 'checkbox-filled',
        '1': 'eye-filled',
        '2': 'close-filled'
      }
      return map[this.detail.checkStatus] || 'checkbox-filled'
    },
    // 结果标题
    resultTitle() {
      const map = {
        '0': '查验通过',
        '1': '需要抽检',
        '2': '查验拒绝'
      }
      return map[this.detail.checkStatus] || '查验通过'
    },
    // 结果描述
    resultDesc() {
      const qrColorMap = {
        '0': '绿码通行',
        '1': '黄码待检',
        '2': '红码禁入'
      }
      return qrColorMap[this.detail.qrColor] || '允许入场'
    }
  },
  onLoad(options) {
    this.checkId = options.id
    this.applyId = options.applyId
    this.loadDetail()
  },
  methods: {
    // 加载详情
    async loadDetail() {
      if (!this.checkId && !this.applyId) {
        uni.showToast({
          title: '参数错误',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        // 如果有checkId，获取查验记录
        if (this.checkId) {
          const res = await getCheckRecord(this.checkId)
          if (res.code === 200 && res.data) {
            this.detail = res.data
            this.processDetail()
          }
        } 
        // 否则通过applyId获取预约详情
        else if (this.applyId) {
          const res = await getAppointment(this.applyId)
          if (res.code === 200 && res.data) {
            // 转换预约数据为查验记录格式
            this.detail = this.convertAppointmentToCheck(res.data)
            this.processDetail()
          }
        }
      } catch (error) {
        console.error('加载详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 转换预约数据为查验记录格式
    convertAppointmentToCheck(appointment) {
      return {
        ...appointment,
        checkTime: appointment.checkTime || appointment.auditTime,
        checkUserName: appointment.checkUserName || appointment.auditBy,
        checkStatus: appointment.checkStatus,
        goodsList: appointment.appointmentDetailList || [],
        certificates: this.processCertificates(appointment.certificateUrls)
      }
    },
    
    // 处理详情数据
    processDetail() {
      // 处理凭证
      if (this.detail.certificateUrls && !this.detail.certificates) {
        this.detail.certificates = this.processCertificates(this.detail.certificateUrls)
      }
      
      // 生成查验记录时间线
      this.generateTimeline()
    },
    
    // 处理凭证图片
    processCertificates(urls) {
      if (!urls) return []
      if (typeof urls === 'string') {
        return urls.split(',').map((url, index) => ({
          url: url.trim(),
          name: `凭证${index + 1}`
        }))
      }
      return urls
    },
    
    // 生成时间线
    generateTimeline() {
      const records = []
      
      // 查验记录
      if (this.detail.checkTime) {
        records.push({
          title: '完成查验',
          desc: `查验人员：${this.detail.checkUserName || '系统'}`,
          time: this.detail.checkTime
        })
      }
      
      // 审核记录
      if (this.detail.auditTime) {
        let title = '审核通过'
        if (this.detail.auditStatus === '2') {
          title = '审核标记需抽检'
        } else if (this.detail.auditStatus === '3') {
          title = '审核拒绝'
        }
        records.push({
          title,
          desc: `审核人：${this.detail.auditBy || '系统'}`,
          time: this.detail.auditTime
        })
      }
      
      // 提交记录
      if (this.detail.createTime) {
        records.push({
          title: '提交预约申请',
          desc: `申请人：${this.detail.merchantName}`,
          time: this.detail.createTime
        })
      }
      
      this.checkRecords = records
    },
    
    // 预览图片
    previewImage(cert) {
      uni.previewImage({
        urls: this.detail.certificates.map(c => c.url),
        current: cert.url
      })
    },
    
    // 处理抽检
    handleInspection() {
      uni.navigateTo({
        url: `/pages/check/inspection?applyId=${this.detail.applyId}`
      })
    }
  }
}
</script>

<style scoped>
.detail-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 结果卡片 */
.result-card {
  margin: 20rpx;
  padding: 40rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  gap: 30rpx;
  color: #fff;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.green-card {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.yellow-card {
  background: linear-gradient(135deg, #faad14, #ffc53d);
}

.red-card {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.result-icon {
  width: 100rpx;
  height: 100rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-info {
  flex: 1;
}

.result-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.result-desc {
  font-size: 28rpx;
  opacity: 0.9;
}

/* 信息区块 */
.info-section {
  background: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  padding-left: 12rpx;
  border-left: 4rpx solid #1890ff;
}

.section-badge {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 6rpx 12rpx;
  background: #fffbe6;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #faad14;
}

.info-list {
  display: flex;
  flex-direction: column;
}

.info-item {
  display: flex;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  width: 160rpx;
  color: #999;
  font-size: 28rpx;
}

.value {
  flex: 1;
  color: #333;
  font-size: 28rpx;
}

/* 商品列表 */
.goods-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.goods-item {
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.goods-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

.inspect-tag {
  display: flex;
  align-items: center;
  gap: 4rpx;
  padding: 4rpx 12rpx;
  background: linear-gradient(135deg, #faad14, #ffc53d);
  border-radius: 20rpx;
  font-size: 22rpx;
  color: #fff;
}

.goods-info {
  font-size: 26rpx;
}

.goods-row {
  display: flex;
  margin-bottom: 8rpx;
}

.goods-label {
  color: #999;
  margin-right: 8rpx;
}

.goods-value {
  color: #666;
}

.inspection-result {
  margin-top: 16rpx;
  padding: 12rpx;
  background: #f6ffed;
  border-radius: 8rpx;
  border-left: 3rpx solid #52c41a;
}

.result-row {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 24rpx;
  color: #52c41a;
  margin-bottom: 8rpx;
}

.result-row:last-child {
  margin-bottom: 0;
}

/* 凭证网格 */
.cert-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.cert-item {
  width: calc(33.33% - 14rpx);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cert-image {
  width: 100%;
  height: 180rpx;
  border-radius: 12rpx;
  background: #f0f0f0;
}

.cert-name {
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
}

/* 时间线 */
.timeline {
  position: relative;
  padding-left: 40rpx;
}

.timeline-item {
  position: relative;
  padding-bottom: 30rpx;
}

.timeline-item:last-child {
  padding-bottom: 0;
}

.timeline-item::before {
  content: '';
  position: absolute;
  left: -30rpx;
  top: 20rpx;
  bottom: 0;
  width: 2rpx;
  background: #e8e8e8;
}

.timeline-item:last-child::before {
  display: none;
}

.timeline-dot {
  position: absolute;
  left: -36rpx;
  top: 8rpx;
  width: 14rpx;
  height: 14rpx;
  background: #fff;
  border: 2rpx solid #d9d9d9;
  border-radius: 50%;
}

.timeline-dot.active {
  background: #1890ff;
  border-color: #1890ff;
  box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.2);
}

.timeline-content {
  background: #f8f9fa;
  padding: 16rpx;
  border-radius: 8rpx;
}

.timeline-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.timeline-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.timeline-time {
  display: flex;
  align-items: center;
  gap: 6rpx;
  font-size: 24rpx;
  color: #999;
}

/* 底部操作 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.95), #fff);
  backdrop-filter: blur(10px);
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  height: 90rpx;
  border-radius: 24rpx;
  font-size: 32rpx;
  font-weight: 600;
  transition: all 0.3s;
  box-shadow: 0 4rpx 16rpx rgba(24, 144, 255, 0.3);
}

.primary-btn {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  color: #fff;
}

.primary-btn:active {
  transform: translateY(2rpx) scale(0.98);
  background: linear-gradient(135deg, #096dd9, #1890ff);
}
</style>